﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Medianamik.Core.Urls
{
    public class RewriteFormHtmlTextWriter : System.Web.UI.HtmlTextWriter
    {
        protected bool ActionAlreadyWritten
        {
            get
            {
                return HttpContext.Current.Items["ActionAlreadyWritten"] != null;
            }
            set
            {
                if (value)
                {
                    HttpContext.Current.Items["ActionAlreadyWritten"] = value;
                }
                else
                {
                    HttpContext.Current.Items.Remove("ActionAlreadyWritten");
                }
            }
        }
        public RewriteFormHtmlTextWriter(System.IO.TextWriter writer):base(writer)
        {
            this.InnerWriter = writer;
        }
        public RewriteFormHtmlTextWriter(System.Web.UI.HtmlTextWriter writer)
            : base(writer)
        {
            // MUST USE .InnerWriter, lest ATLAS breaks
            this.InnerWriter = writer.InnerWriter;
        }
        public override void WriteAttribute(string name, string value, bool fEncode)
        {
            if (name == "action")
            {
                if (!ActionAlreadyWritten)
                {
                    value = HttpContext.Current.Request.RawUrl;
                    ActionAlreadyWritten = true;
                }
            }
            base.WriteAttribute(name, value, fEncode);
        }
    }
}
